//
//  QDQuestionFeedViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/3.
//  Copyright © 2019 YueWen. All rights reserved.
//

//// 代码结构很差，木有办法，谁让领导10天要求从头写一个青岛地铁APP呢？
/// TODO: 日后需要重构！

import UIKit

private extension QDQuestionFeedViewController.QDQuestionFeedCells {
    
    /// 对应的cell类
    var cellClass: AnyClass {
        get {
            switch self {
            case .type: return QDQuesTypeTableViewCell.self
            case .text: return QDQuesTextTableViewCell.self
            case .photo: return QDQuesPhotoTableViewCell.self
            case .phone: return QDQuesPhoneTableViewCell.self
            }
        }
    }
    
    /// cell的高度
    var cellHeight: CGFloat {
        get {
            switch self {
            case .type: return 130
            case .text: return 254
            case .photo: return CGFloat(QDQuesPhotoTableViewCell.itemSize + 46 + 32)
            case .phone: return 73
            }
        }
    }
}



/// 进行内容配置
private extension QDQuestionFeedViewController.QDQuestionFeedType {
    
    /// 标题的问题描述
    var itemTitle: String {
        get {
            switch self {
            case .question: return "问题描述"
            case .questionForApp: return "产品意见反馈"
            }
        }
    }
    
    /// 列表的样式
    var tableViewCellTypes: [QDQuestionFeedViewController.QDQuestionFeedCells]{
        get {
            switch self{
            case .question: return QDQuestionFeedViewController.QDQuestionFeedCells.allCases
            case .questionForApp: return [.text,.photo,.phone]
            }
        }
    }
    
    /// 问题的描述
    var questDesc: String {
        get {
            switch self {
            case .question: return "请简单描述您的问题（必填）"
            case .questionForApp: return "意见反馈（必填）"
            }
        }
    }
    
    /// 问题的占位符
    var questPlaceholder: String {
        get {
            switch self {
            case .question: return "在这里描述你的问题吧~"
            case .questionForApp: return "对我们APP还有什么建议吗？你还期望APP有哪些功能和改进？在这里告诉我们吧！"
            }
        }
    }
}


/// 反馈信息的容器，可以有产品意见反馈/问题描述
fileprivate struct QDQuestionFeedContainer {
    
    /// 问题的id
    var questionId = "1"
    /// 问题的描述
    var questionTitle = "地铁APP"
    /// 问题的内容
    var questionContent = ""
    /// 图片资源id
    var questionImageAssetIds = [String]()
    /// 问题截图
    var questionImages = [UIImage]()
    /// 问题截图的url
    var questionImageUrls = [String]()
    /// 联系方式
    var questionPhone = ""
}







fileprivate extension QDQuestionFeedContainer {
    
    var paramters: [String: Any] {
        get {
            return ["Phone":questionPhone,"describe":questionContent,"Img": (questionImageUrls as NSArray).componentsJoined(by: ","),"questionType": questionId]
        }
    }
}





/// 问题描述/反馈界面
final class QDQuestionFeedViewController: NWTableViewController,QDLargeTitleTableHeaderScrollable,NWNetWorkingUploaderAction {

    /// 问题描述的cell
    enum QDQuestionFeedCells: String,CaseIterable {
        /// 问题类型
        case type
        /// 问题描述
        case text
        /// 截图描述
        case photo
        /// 手机号
        case phone
    }
    
    /// 问题反馈的类型
    enum QDQuestionFeedType {
        /// 问题反馈
        case question
        /// 产品意见反馈
        case questionForApp
    }
    
    
    /// 反馈类型，默认为常用的问题反馈
    private var feedType: QDQuestionFeedType = .question {
        willSet {
            if newValue == .question { return }
            // 产品反馈
            feedContainer.questionId = "7"//产品意见反馈
        }
    }
    
    
    /// 反馈信息容器
    fileprivate var feedContainer = QDQuestionFeedContainer()
    /// 模拟大标题
    let largeTableHeaderView = QDLargeTitleTableHeaderView()
    /// 上传
    let updateLoader = NWNetWorkingUploader()
    
    /// 放置提交按钮的footer
    private lazy var footerView: UIView = {
        
        let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 64 + (hasPhoneHeader() ? 0 : 20))))
        
        // layer
        let gradLayer = CAGradientLayer()
        gradLayer.anchorPoint = .zero
        gradLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradLayer.endPoint = CGPoint(x: 1, y: 0.5)
        gradLayer.colors = [#colorLiteral(red: 0.4509803922, green: 0.8705882353, blue: 0.5215686275, alpha: 1).cgColor,QDColors.theme.cgColor]
        gradLayer.bounds = CGRect(origin: .zero, size: CGSize(width: ritl_width - 40, height: 44))
        
        // button
        let button = UIButton()
        button.adjustsImageWhenHighlighted = false
        button.setTitle("提交", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = Font.medium.font(size: 16)
        button.layer.insertSublayer(gradLayer, at: 0)
        button.layer.cornerRadius = 23
        button.clipsToBounds = true
        
        view.addSubview(button)
        
        button.snp.makeConstraints({ (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20).priority(.high)
            make.height.equalTo(44)
            make.top.equalToSuperview().offset(20)
        })
        
        button.addTarget(self, action: #selector(send), for: .touchUpInside)
        
        return view
    }()
    
    /// 电话
    private var servicePhone = ""
    
    
    convenience init(type: QDQuestionFeedType = .question) {
        
        self.init()
        feedType = type
       
        if type == .questionForApp {
            feedContainer.questionId = "7"
        }
    }

    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        for type in QDQuestionFeedCells.allCases {
            tableView.register(type.cellClass, forCellReuseIdentifier: type.rawValue)
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        largeTableHeaderView.title = feedType.itemTitle
        largeTableHeaderView.ritl_width = ritl_width
        largeTableHeaderView.ritl_height = QDLargeTitleTableHeaderViewNormalHeight
        tableView.tableHeaderView = largeTableHeaderView
        
        //footer
        tableView.tableFooterView = footerView
        
        //数据
        if QDUserStatus.isLogin {
            feedContainer.questionPhone = QDUserInfoModelObjc.phone
        }
        
        //进行网络上传
        updateLoader.url = QDStaticHostUrl + "/static/upload"
        updateLoader.fileSuffix = "png"
        updateLoader.fileName = "file"
        updateLoader.mimeType = "image/png"
        updateLoader.delegate = self
        updateLoader.fileMaxSize = 800
        updateLoader.serviceName = "file"
        updateLoader.parameters = ["token":QDUserInfoModel.share.token]
        
        //TODO: 请求客服电话
        QDNetworkingManager.requestStaticData(success: { (data) in
            
            //获得电话
            self.servicePhone = data[QDNetworkingManager.StaticType.serviceTel.rawValue] as? String ?? ""
            
        }) { (msg, errorType) in }

    }
    
    
    // MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    

    // MARK: UIScrollViewDelegate
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        tableViewDidScroll(contentOfset: scrollView.contentOffset) { (isShow) in
            setNavigationBarShadowViewHidden(!isShow)
        }
    }
    
    
    // MARK: UITableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return feedType.tableViewCellTypes.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let type = feedType.tableViewCellTypes[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: type.rawValue, for: indexPath)
        
        
        /// 类型类型cell
        if let typeCell = cell as? QDQuesTypeTableViewCell {
            typeCell.currentId = feedContainer.questionId
            //设置想一个回调
            typeCell.didSelectItemHandler = { [unowned self] (id, _) in
                self.feedContainer.questionId = id
            }
        }
        
            
        /// 问题描述
        else if let contentCell = cell as? QDQuesTextTableViewCell {
            
            contentCell.titleLabel.text = feedType.questDesc
            contentCell.textView.placeholder = feedType.questPlaceholder as NSString
            contentCell.textView.text = feedContainer.questionContent

            /// 结束
            contentCell.endHandler = { [unowned self] (textView) in
                self.feedContainer.questionContent = textView.text
            }
        }
        
            
        /// 照片的cell
        else if let photoCell = cell as? QDQuesPhotoTableViewCell {
            photoCell.photoDelegate = self
            photoCell.images = feedContainer.questionImages
        }
        
            
        /// 联系方式的cell
        else if let phoneCell = cell as? QDQuesPhoneTableViewCell {
            phoneCell.textField.delegate = self
            phoneCell.textField.text = feedContainer.questionPhone
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return feedType.tableViewCellTypes[indexPath.row].cellHeight
    }
    
    
    // MARK: objc
    @objc func send(){
        
        view.endEditing(true)
        
        //开始检测
        if feedContainer.questionContent.isEmpty {
            view.showTextHUD(text: "请填写您的问题"); return
        }
    
        if (feedContainer.questionContent as NSString).length > 100 {
            view.showTextHUD(text: "描述超出字数限制"); return
        }
    
        if feedContainer.questionPhone.isEmpty || !RITLFilter.phone(feedContainer.questionPhone){
            view.showTextHUD(text: "请正确填写您的联系方式"); return
        }
    
        if feedContainer.questionImages.count > 0 {//进行图片上传
            
            view.showTextHUD(text: "正在上传图片",delayHidden: 10)
            updateLoader.files = feedContainer.questionImages
            updateLoader.resumeUpdate(); return
        }
    
        view.showTextHUD(text: "反馈中...",delayHidden: 10)
        updateFeedBackMessage()
    }
    
    
    /// 上传反馈内容
    func updateFeedBackMessage(){
        
        //进行参数拼接
        let parameters = feedContainer.paramters
        
        /// $$$$$
        QDNetworkingManager.request(url: QDCustomerHostUrl + "/user/userAdvice", paramteres: parameters, success: { (msg, data) in
            
            self.view.dismissHUD()
            
            if self.feedType == .question {
                self.showAlert(); return
            }
            
            //产品意见反馈
            self.view.showTextHUD(text: "您的建议已经记录,感谢反馈")
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }) { (msg, errorType) in
            
            self.view.showTextHUD(text: msg)
        }
    }
    
    
    /// 展示拨打地铁客服热线
    private func showAlert(){
        
        let alertController = ASPopupController.alert(withTitle: "您的建议已经记录,感谢反馈,是否还需要拨打客服热线?", message: nil)
        
        
        alertController.add(ASPopupAction(title: "人工客服", style: .qdMetroCancel, handler: {
            
            if self.servicePhone.isEmpty {
                self.view.showTextHUD(text: "电话号码异常，请退出重新进入!"); return
            }
            
            RITLCall(self.servicePhone) //拨打
            self.navigationController?.popViewController(animated: true)
        }))
        
        
        alertController.add(ASPopupAction(title: "不需要了", style: .qdMetroCancel, handler: {
            self.navigationController?.popViewController(animated: true)
        }))
        

        
        /// 弹出视图
        present(alertController, animated: true, completion: nil)
        
//        let alertView = UIAlertController(title: nil, message: "您的建议已经记录,感谢反馈,是否还需要拨打客服热线?", preferredStyle: .alert)
        
        /// 不需要了
//        alertView.addAction(UIAlertAction(title: "不需要了", style: .default , handler: { (_) in
//            self.navigationController?.popViewController(animated: true)
//        }))
//        
//        alertView.addAction(UIAlertAction(title: "人工客服", style: .cancel, handler: { (_) in
//            
//            if self.servicePhone.isEmpty {
//                self.view.showTextHUD(text: "电话号码异常，请退出重新进入!"); return
//            }
//            
//            //拨打
//            RITLCall(self.servicePhone)
//            self.navigationController?.popViewController(animated: true)
//        }))
//        
//        /// 弹出视图
//        present(alertView, animated: true, completion: nil)
    }
    
    
    
    
    // MARK: NWNetWorkingUploaderAction
    func netWorkingUploader(_ netWorkingUploader: NWNetWorkingUploader, completeWithData info: [Any]) {
        
        var imageUrls = [String]()
        //开始遍历
        for (_, data) in info.enumerated() {
            if let item = data as? [String: Any], let url = item["data"] as? String {
                imageUrls.append(url)
            }
        }
        
        feedContainer.questionImageUrls = imageUrls
        view.showTextHUD(text: "图片上传成功,开始提交反馈")
        updateFeedBackMessage()
    }
    
    func netWorkingUploader(_ netWorkingUploader: NWNetWorkingUploader, progress current: Int, fail error: Error) {
        
        view.dismissHUD()
        view.showTextHUD(text: "\(error.localizedDescription)")
    }
    
}


extension QDQuestionFeedViewController: UITextFieldDelegate,UITextViewDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        feedContainer.questionPhone = textField.text ?? ""
    }
}


extension QDQuestionFeedViewController: QDQuesPhotoTableViewCellDelegate {
    
    func quesPhotoTableViewCell(cell: QDQuesPhotoTableViewCell, action: QDQuesPhotoTableViewCell.PhotoActionType, at indexPath: IndexPath) {
        
        /// add 进行响应
        func actionTypeForAdd(){
           
            let photoPickerView = RITLPhotosViewController()
            photoPickerView.navigationBar.tintColor = QDColors.theme
            photoPickerView.configuration.containVideo = false
            photoPickerView.configuration.hiddenGroupWhenNoPhotos = true
            photoPickerView.configuration.maxCount = 3
            photoPickerView.photo_delegate = self
            let size = UIScreen.main.ritl_width > 370 ? 80 : Int((UIScreen.main.ritl_width - 40 - 3) / 4)
            photoPickerView.thumbnailSize = CGSize(width: size, height: size)
            photoPickerView.defaultIdentifers = feedContainer.questionImageAssetIds
            
            //跳转到相册
            present(photoPickerView, animated: true, completion: nil)
        }
        
        /// remove 响应
        func actionTypeForRemove(){
            
            let item = indexPath.item
            feedContainer.questionImageAssetIds.remove(at: item)
            feedContainer.questionImages.remove(at: item)
            //刷新视图
            tableView.reloadData()
        }
        
        
        if action == .add {
            actionTypeForAdd(); return
        }
        
        actionTypeForRemove()
    }
}


extension QDQuestionFeedViewController: RITLPhotosViewControllerDelegate {
    
    
    func photosViewController(_ viewController: UIViewController, assetIdentifiers identifiers: [String]) {
        feedContainer.questionImageAssetIds = identifiers
    }
    
    
    func photosViewController(_ viewController: UIViewController, images: [UIImage], infos: [[AnyHashable : Any]]) {
        feedContainer.questionImages = images
        //刷新视图
        tableView.reloadData()
    }
    
}





